package org.edu.service;

import java.util.Date;
import java.util.List;

import org.edu.common.PageConstants;
import org.edu.common.uiltst.Dateutil;
import org.edu.common.vo.PageResult;
import org.edu.dao.EmpDao;
import org.edu.dao.UserDao;
import org.edu.model.Emp;
import org.edu.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = { RuntimeException.class }, propagation = Propagation.REQUIRED)
public class EmpService extends ServiceAdapter<Emp, Integer> {
	@Autowired
	private EmpDao empDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private PageConstants constants;

	@Override
	public Emp show(Integer id) {
		// TODO Auto-generated method stub
		return empDao.get(id);
	}

	@Override
	public List<Emp> list() {
		// TODO Auto-generated method stub
		return empDao.loadAll();
	}

	/**
	 * 查询部门下所有用户
	 * 
	 * @param e
	 *            需要查询的部门
	 * @param currentPage
	 *            第几页
	 * @return
	 */
	public PageResult<User> pageResault(Emp e, int currentPage) {

		if (currentPage <= 0) {
			currentPage = 1;
		}

		String hql = buildHqlStr(e.getEmpno());
		List<User> l = userDao.find(hql,
				(currentPage - 1) * constants.getPageMax(),
				constants.getPageMax());

			Date d1=null;
			Date d2=null;
			for (User u : l) {
				d1=u.getOffline();
				d2=u.getLasttime();
				if(d1!=null)
					u.setOfftime(Dateutil.getQuot(d1, new Date()));
				else u.setOfftime("从未登录");
				if(d2!=null) u.setOnline(Dateutil.getQuot(d2, new Date()));
				else u.setOnline("从未上线");
			}
		
		// 获取总个数
		int allPage = userDao.getCount(hql);
		PageResult<User> result = new PageResult<User>(l, allPage, currentPage,
				constants.getPageMax());

		return result;
	}

	/**
	 * 根据查询条件动态生成HQL语句
	 * 
	 * @return
	 */
	private String buildHqlStr(int empno) {
		String hql = "from User where empid =" + empno
				+ " order by account";
		System.out.println("generate :" + hql);

		return hql;
	}

}
